package com.ybkj.daijia.api.member.v2;

import com.ybkj.daijia.api.member.ErrorConstant;
import com.ybkj.daijia.api.member.SecurityUtils;
import com.ybkj.daijia.api.member.transport.ResultTransport;
import com.ybkj.daijia.common.IdcardUtils;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderService;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;

/**
 *
 */
@Controller("MemberAccountV2Controller")
@RequestMapping(value = "member/api/rest/v2")
public class MemberAccountController {

    private static final Logger logger = LoggerFactory.getLogger(MemberAccountController.class);

    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberAccountService memberAccountService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private OrderService orderService;


    /**
     * 完善用户信息
     *
     * @param phone     手机号
     * @param appKey
     * @param token     token令牌
     * @param timestamp 时间戳
     * @return
     */
    @RequestMapping(value = "updateInfo", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport updateInfo(
        HttpServletRequest req,
        @RequestParam(required = false, value = "photo") MultipartFile photoFile,
        String phone, String realName, String idCard, String email, String appKey, String token,
        String timestamp) {

        logger.debug("recv phone:{},realName:{},idCard:{},email:{},appKey:{},token:{},timestamp:{}",
            phone, realName, idCard, email, appKey, token, timestamp);

        if (StringUtils.isBlank(phone) || StringUtils.isBlank(realName) || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        if (StringUtils.isNotBlank(email)) {
            String check = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            boolean isMatched = matcher.matches();
            if (!isMatched) {
                return ResultTransport.getErrorBy(ErrorConstant.EMAIL_ERROR);
            }
        }

        if (StringUtils.isNotBlank(idCard)) {
            if (!IdcardUtils.validateCard(idCard)) {
                return ResultTransport.getErrorBy(ErrorConstant.IDCARD_ERROR);
            }
        }

        List<String> params = new LinkedList<String>();
        params.add(phone);
        params.add(realName);
        params.add(idCard);
        params.add(email);
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {
            Passenger passenger = memberService.findOnePassengerByPhone(phone);

            if (null == passenger) {
                return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS_ERROR);
            }

            if (null != photoFile) {
                try {
                    String bathPath = getBasePath(req);

                    File dir = new File(bathPath, "upload/member");

                    FileUtils.forceMkdir(dir);

                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

                    String fileName = String
                        .format("%s.png", df.format(new Date()) + "_" + new Random().nextInt(1000));

                    byte[] data = photoFile.getBytes();
                    FileOutputStream out = new FileOutputStream(new File(dir, fileName));
                    IOUtils.write(data, out);
                    IOUtils.closeQuietly(out);

                    passenger.setPhoto(fileName);
                } catch (Exception e) {
                    logger.debug(e.getMessage());
                }
            }

            passenger.setName(realName);
            passenger.setIdcard(idCard);
            passenger.setEmail(email);

            Result<Passenger> result = memberService.updatePersonal(passenger);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(result.getResult());

            return instance;

        } catch (Exception e) {
            logger.error("api v2 member updateInfo error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    private String getBasePath(HttpServletRequest req) {

        try {
            return WebUtils.getRealPath(req.getSession().getServletContext(), "/");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return StringUtils.EMPTY;
    }

}
